import { Order } from '../../utils/order-model.js';
var order = new Order();
import { Product } from '../../utils/product-model.js';
var product = new Product();
import { Pay } from '../../utils/pay-model.js';
var pay = new Pay();
let videoAd = null
Page({
  data: {
    ind:0,
    score:0,
    beforescore:0,
    fromnb:0//0表示正常顺序，1表示来自上一题
  },
  onLoad: function (options) {
    var that = this;
    var id = options.id;//订单id
    //var order_no = options.order_no;//订单号
    var one = wx.getStorageSync('one');
    that.setData({
      //order_no: order_no,
      id: id,//订单id
      one: one,
      questions:one.questions
    })
    that.setData({
          adif: getApp().globalData.adif,
        });
//今日头条//今日头条lite//抖音版本太低
    if((getApp().globalData.adif == 0) || (getApp().globalData.adif == 2)){

    }else{
        if (tt.createRewardedVideoAd) {
      videoAd = tt.createRewardedVideoAd({
        adUnitId: 'ida6o3aroa86770f4h'
      })
      videoAd.onLoad(() => { })
      videoAd.onError((err) => { })
      videoAd.onClose((res) => { 
        if (res && res.isEnded) {
          //console.log('正常播放结束，可以下发游戏奖励')
          //商品product_id
            //订单id
            //console.log('that.data.id:' + that.data.id);
            //根据商品id获取解析结果
            var id = that.data.id;//订单id
            var product_id = that.data.one.id;//商品id
            var score = that.data.score;//分值
            
            //更新订单
            product.getAnswerData(id, product_id, score, (data) => {
              console.log("0000000000000000000000000000000000");
              console.log("OrderResultOne"); console.log(data);
              wx.setStorageSync('OrderResultOne', data);//获取结果对象并保存在缓存
              wx.redirectTo({
                //url: 'result?from=1&id=' + that.data.id + '&product_id=' + that.data.one.id+'&score='+that.data.score,
                url: 'result?from=1&id=' + id + '&product_id=' + product_id + '&score=' + score,
              })
            });
        }else{
          //console.log('播放中途退出，不下发游戏奖励')
        }
      })
        }
    }
  },

  bindtapSelect: function (e) {
    var that = this;
    let index = e.currentTarget.dataset["index"];//某一题目某一选项索引
    let questions = that.data.questions;
    let ind = that.data.ind;
    let olength = questions[ind].options.length;
    let option = questions[ind].options[index];
    console.log("that.data.fromnb:" + that.data.fromnb);
    if (that.data.fromnb == 1) {
      for (let i = 0; i < olength; i++) {
        //先把之前选择的数据score分值去除
        if (questions[ind].options[i].checked) {
          let realscore = that.data.score - questions[ind].options[i].score;
          let score = realscore + option.score;//获取当前选择项的分值
          console.log('score:' + score);
          that.setData({
            score: score,
            fromnb: 0
          })
        }
      }
      that.getQuestions(questions, olength, ind, index);
    }else{
      that.getQuestions(questions, olength, ind, index);
      console.log('ind:'+ind);
      console.log('questions.length:'+questions.length);
      if (ind == (questions.length - 1)) {
        let score = that.data.score - that.data.beforescore + option.score;//获取当前选择项的分值
        console.log('score:' + score);
        console.log('beforescore:' + option.score);
        that.setData({
          beforescore: option.score,
          score: score,
        })
        return;
      }
      let score = that.data.score + option.score;//获取当前选择项的分值
      console.log('score:' + score);
      that.setData({
        score: score
      })
    }
    that.setData({
      ind: ind + 1
    })
  },

  bindtapBefore:function(e){
    var that = this;
    console.log(that.data.ind);
    if(that.data.ind != 0){
      that.setData({
      ind: that.data.ind - 1,
      fromnb: 1
    })
    }
    
  },

  bindtapSubmit:function(e){
    var that = this;
    if(that.data.beforescore != 0){
      if (that.data.ind == (that.data.questions.length - 1)) {
if((getApp().globalData.adif == 0) || (getApp().globalData.adif == 2)){
var id = that.data.id;//订单id
            var product_id = that.data.one.id;//商品id
            var score = that.data.score;//分值
            
            //更新订单
            product.getAnswerData(id, product_id, score, (data) => {
              console.log("0000000000000000000000000000000000");
              console.log("OrderResultOne"); console.log(data);
              wx.setStorageSync('OrderResultOne', data);//获取结果对象并保存在缓存
              wx.redirectTo({
                //url: 'result?from=1&id=' + that.data.id + '&product_id=' + that.data.one.id+'&score='+that.data.score,
                url: 'result?from=1&id=' + id + '&product_id=' + product_id + '&score=' + score,
              })
            });
    }else{
      if (videoAd) {
          videoAd.show().catch(() => {
            // 失败重试
            videoAd.load()
              .then(() => videoAd.show())
              .catch(err => {
                console.log('激励视频 广告显示失败')
              })
          })
        }
        return;
      }
    }
    }

    
  },

  getQuestions: function (questions, olength, ind, index){
    var that = this;
    for (let i = 0; i < olength; i++) {
      if (index == i) {
        //当前点击的位置为true即选中
        questions[ind].options[i].checked = true;
      } else {
        //其他的位置为false
        questions[ind].options[i].checked = false;
      }
    }
    that.setData({
      questions: questions
    })
    console.log(questions);
  },
  /*
  * 微信开始支付
  * params:
  * id - {int}订单id
  */
  _execPay: function (id, product_id, score) {
    console.log("_execPay:"+id);
    var that = this;
    pay.execPay(id, (data) => {
      console.log("pay");
      console.log(data);
        tt.pay({
          orderInfo: data,
          service: 1,
          //_debug:1,
          getOrderStatus(res) {
            console.log('getOrderStatus');
            console.log(res);
            console.log(res.out_order_no);
            that.setData({
              order_no:res.out_order_no
            })
            return new Promise(function(resolve, reject) {
              wx.request({
                url: 'https://x.xiaocenxu.com/api/v1/pay/check',
                method: 'post',
                data: { 
                  tradeno: res.out_order_no
                },
                header: {
                  'content-type': 'application/json',
                  'token': wx.getStorageSync('token')
                },
                success: function (rs) {
                  console.log("ffffffffffff");console.log(rs);console.log("eeeeeeeeeeeeeeeeeeeee");
                  if(rs.data.status == 0){
                    //支付成功,执行关闭支付窗口
                    //let { out_order_no } = rs;
                   resolve({ code: 0});//订单id
                  }else if(rs.data.status == 4){
                   resolve({ code: 4});
                  }else if(rs.data.status == 3){
                   resolve({ code: 3});
                  }else{
                    resolve({ code: 2});
                    //0：支付成功 1：支付超时 2：支付失败 3：支付关闭 4：支付取消 
                    //9：订单状态开发者自行获取。
                    //只要调起收银台成功，支付状态都会回调success返回，开发者依据返回的 code 值，进行后续业务逻辑处理
                  }
                }
              });
            });
          },
          success(res) {
            console.log('success');console.log(res);
            if (res.code == 0) {
              var id = that.data.id;
              //console.log('id');console.log(res);console.log(res.id);console.log('detail id');
              wx.navigateTo({
                url: 'result?id='+id
              })
            }else if (res.code == 3) {
            }else{
            }
          },
          fail(res) {
            console.log('fail2');console.log(res);
            tt.showToast({
              title: res.errMsg, // 内容
              success: (res) => {
              }
            });
           }
        });
    });
  },

   onShareAppMessage (option) {
    // option.from === 'button'
    return {
      title: '点击测试【全网888万人在免费测试】',
      desc: '提供优质的智商测试、性格测试、爱情测试、趣味测试',
      path: '/pages/home/home', // ?后面的参数会在转发页面打开时传入onLoad方法
      imageUrl: '/images/logo.png', // 支持本地或远程图片，默认是小程序icon
      templateId: 'bb87ln5ge3e3cgfca8',
      success () {
        //console.log('转发发布器已调起，并不意味着用户转发成功，微头条不提供这个时机的回调');
      },
      fail () {
        //console.log('转发发布器调起失败');
      }
    }
  }
}) 